<template>
  <div class="exposure-audit">
    <div class="page-header">
      <h1>曝光台审核</h1>
      <p>管理曝光台帖子内容的审核和维护</p>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stats-card total-posts">
            <div class="stats-content">
              <div class="stats-number">{{ stats.total_posts }}</div>
              <div class="stats-label">总帖子数</div>
            </div>
            <el-icon class="stats-icon"><Document /></el-icon>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card today-posts">
            <div class="stats-content">
              <div class="stats-number">{{ stats.today_posts }}</div>
              <div class="stats-label">今日发布</div>
            </div>
            <el-icon class="stats-icon"><Calendar /></el-icon>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card total-comments">
            <div class="stats-content">
              <div class="stats-number">{{ stats.total_comments }}</div>
              <div class="stats-label">总评论数</div>
            </div>
            <el-icon class="stats-icon"><ChatDotRound /></el-icon>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card total-likes">
            <div class="stats-content">
              <div class="stats-number">{{ stats.total_likes }}</div>
              <div class="stats-label">总点赞数</div>
            </div>
            <el-icon class="stats-icon"><Star /></el-icon>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 搜索和筛选 -->
    <el-card class="filter-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="搜索">
          <el-input
            v-model="searchForm.search"
            placeholder="搜索帖子内容或用户昵称"
            clearable
            style="width: 250px"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="发布时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 240px"
            @change="handleSearch"
          />
        </el-form-item>
        <el-form-item label="排序">
          <el-select v-model="searchForm.sortBy" style="width: 120px" @change="handleSearch">
            <el-option label="发布时间" value="created_at" />
            <el-option label="点赞数" value="like_count" />
            <el-option label="评论数" value="comment_count" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 帖子列表 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>曝光台帖子列表</span>
          <el-button @click="refreshList" :loading="loading">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </template>

      <el-table
        :data="postsList"
        v-loading="loading"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="发布者" width="120">
          <template #default="{ row }">
            <div class="user-info">
              <el-avatar :size="30" :src="row.users?.avatar_url">
                {{ row.users?.nickname?.charAt(0) }}
              </el-avatar>
              <span>{{ row.users?.nickname || '未知用户' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="帖子内容" min-width="300">
          <template #default="{ row }">
            <div class="post-content">
              <p class="content-text">{{ truncateText(row.content, 100) }}</p>
              <div v-if="row.images && row.images.length > 0" class="content-meta">
                <el-tag size="small" type="info">
                  <el-icon><Picture /></el-icon>
                  {{ row.images.length }}张图片
                </el-tag>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="互动数据" width="150">
          <template #default="{ row }">
            <div class="interaction-stats">
              <div>
                <el-icon><Star /></el-icon>
                {{ row.like_count }}
              </div>
              <div>
                <el-icon><ChatDotRound /></el-icon>
                {{ row.comment_count }}
              </div>
              <div>
                <el-icon><Share /></el-icon>
                {{ row.share_count }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="发布时间" width="160">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button
                type="primary"
                size="small"
                @click="viewPost(row)"
              >
                查看详情
              </el-button>
              <el-button
                type="warning"
                size="small"
                @click="editPost(row)"
              >
                编辑
              </el-button>
              <el-popconfirm
                title="确定要删除这个帖子吗？"
                @confirm="deletePost(row.id)"
              >
                <template #reference>
                  <el-button
                    type="danger"
                    size="small"
                  >
                    删除
                  </el-button>
                </template>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 帖子详情对话框 -->
    <el-dialog
      v-model="detailDialog.visible"
      title="帖子详情"
      width="800px"
      :close-on-click-modal="false"
    >
      <div v-if="detailDialog.post" class="post-detail">
        <div class="detail-section">
          <h3>发布者信息</h3>
          <div class="user-detail">
            <el-avatar :size="50" :src="detailDialog.post.users?.avatar_url">
              {{ detailDialog.post.users?.nickname?.charAt(0) }}
            </el-avatar>
            <div class="user-meta">
              <p><strong>昵称：</strong>{{ detailDialog.post.users?.nickname }}</p>
              <p><strong>手机号：</strong>{{ detailDialog.post.users?.phone_number }}</p>
            </div>
          </div>
        </div>

        <div class="detail-section">
          <h3>帖子内容</h3>
          <p class="post-text">{{ detailDialog.post.content }}</p>
          
          <div v-if="detailDialog.post.images && detailDialog.post.images.length > 0" class="post-images">
            <el-image
              v-for="(img, index) in detailDialog.post.images"
              :key="index"
              :src="getFullImageUrl(img)"
              fit="cover"
              style="width: 100px; height: 100px; margin-right: 10px; margin-bottom: 10px;"
              @click="previewImages(detailDialog.post.images.map(getFullImageUrl), index)"
            />
          </div>
        </div>

        <div class="detail-section">
          <h3>互动统计</h3>
          <div class="stats-detail">
            <el-tag>点赞数：{{ detailDialog.post.like_count }}</el-tag>
            <el-tag>评论数：{{ detailDialog.post.comment_count }}</el-tag>
            <el-tag>分享数：{{ detailDialog.post.share_count }}</el-tag>
          </div>
        </div>

        <div class="detail-section">
          <h3>最近评论</h3>
          <div v-if="detailDialog.post.exposure_comments && detailDialog.post.exposure_comments.length > 0" class="comments-list">
            <div
              v-for="comment in detailDialog.post.exposure_comments"
              :key="comment.id"
              class="comment-item"
            >
              <div class="comment-user">
                <strong>{{ comment.users?.nickname }}</strong>
                <span class="comment-time">{{ formatDate(comment.created_at) }}</span>
              </div>
              <p class="comment-content">{{ comment.content }}</p>
              <el-button
                type="danger"
                size="small"
                text
                @click="deleteComment(comment.id)"
              >
                删除评论
              </el-button>
            </div>
          </div>
          <p v-else class="no-comments">暂无评论</p>
        </div>
      </div>
    </el-dialog>

    <!-- 编辑帖子对话框 -->
    <el-dialog
      v-model="editDialog.visible"
      title="编辑帖子"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form :model="editForm" label-width="80px">
        <el-form-item label="帖子内容">
          <el-input
            v-model="editForm.content"
            type="textarea"
            :rows="8"
            placeholder="请输入帖子内容"
            maxlength="2000"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="图片">
          <div class="image-list">
            <div
              v-for="(img, index) in editForm.images"
              :key="index"
              class="image-item"
            >
              <el-image
                :src="getFullImageUrl(img)"
                fit="cover"
                style="width: 80px; height: 80px;"
              />
              <el-button
                type="danger"
                size="small"
                circle
                class="remove-image"
                @click="removeImage(index)"
              >
                <el-icon><Close /></el-icon>
              </el-button>
            </div>
          </div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="editDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="savePost" :loading="editDialog.loading">
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Document,
  Calendar,
  ChatDotRound,
  Star,
  Search,
  Refresh,
  Share,
  Close,
  Picture
} from '@element-plus/icons-vue'
import { exposureApi } from '@/api/admin'
import { getFullImageUrl } from '@/utils/request'

// 数据定义
const loading = ref(false)
const stats = ref({
  total_posts: 0,
  today_posts: 0,
  total_comments: 0,
  total_likes: 0
})

const searchForm = reactive({
  search: '',
  dateRange: null as null | [Date, Date],
  sortBy: 'created_at'
})

const postsList = ref<any[]>([])
const pagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0
})

const detailDialog = reactive({
  visible: false,
  post: null as any
})

const editDialog = reactive({
  visible: false,
  loading: false
})

const editForm = reactive({
  id: '',
  content: '',
  images: [] as string[]
})

// 方法定义
const loadStats = async () => {
  try {
    const response = await exposureApi.getStats()
    stats.value = response.data
  } catch (error) {
    console.error('获取统计信息失败:', error)
  }
}

const loadPostsList = async () => {
  loading.value = true
  try {
    const params: any = {
      page: pagination.page,
      pageSize: pagination.pageSize,
      sortBy: searchForm.sortBy,
      sortOrder: 'desc'
    }

    if (searchForm.search) {
      params.search = searchForm.search
    }

    if (searchForm.dateRange) {
      params.startDate = searchForm.dateRange[0].toISOString().split('T')[0]
      params.endDate = searchForm.dateRange[1].toISOString().split('T')[0]
    }

    const response = await exposureApi.getPostsList(params)
    postsList.value = response.data.items
    pagination.total = response.data.total
  } catch (error) {
    ElMessage.error('获取帖子列表失败')
    console.error('获取帖子列表失败:', error)
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.page = 1
  loadPostsList()
}

const handleReset = () => {
  searchForm.search = ''
  searchForm.dateRange = null
  searchForm.sortBy = 'created_at'
  pagination.page = 1
  loadPostsList()
}

const handleSizeChange = (newSize: number) => {
  pagination.pageSize = newSize
  pagination.page = 1
  loadPostsList()
}

const handleCurrentChange = (newPage: number) => {
  pagination.page = newPage
  loadPostsList()
}

const refreshList = () => {
  loadStats()
  loadPostsList()
}

const viewPost = async (post: any) => {
  try {
    const response = await exposureApi.getPostDetail(post.id)
    detailDialog.post = response.data
    detailDialog.visible = true
  } catch (error) {
    ElMessage.error('获取帖子详情失败')
  }
}

const editPost = (post: any) => {
  editForm.id = post.id
  editForm.content = post.content
  editForm.images = [...post.images]
  editDialog.visible = true
}

const savePost = async () => {
  if (!editForm.content.trim()) {
    ElMessage.error('帖子内容不能为空')
    return
  }

  editDialog.loading = true
  try {
    await exposureApi.updatePost(editForm.id, {
      content: editForm.content,
      images: editForm.images
    })
    
    ElMessage.success('编辑成功')
    editDialog.visible = false
    loadPostsList()
  } catch (error) {
    ElMessage.error('编辑失败')
  } finally {
    editDialog.loading = false
  }
}

const deletePost = async (postId: string) => {
  try {
    await exposureApi.deletePost(postId)
    ElMessage.success('删除成功')
    loadPostsList()
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

const deleteComment = async (commentId: string) => {
  try {
    await ElMessageBox.confirm('确定要删除这条评论吗？', '提示')
    await exposureApi.deleteComment(commentId)
    ElMessage.success('删除评论成功')
    
    // 刷新帖子详情
    if (detailDialog.post) {
      viewPost(detailDialog.post)
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('删除评论失败')
    }
  }
}

const removeImage = (index: number) => {
  editForm.images.splice(index, 1)
}

const previewImages = (images: string[], index: number) => {
  // 这里可以使用 Element Plus 的图片预览组件
  console.log('预览图片', images, index)
}

const truncateText = (text: string, maxLength: number) => {
  return text.length > maxLength ? text.substring(0, maxLength) + '...' : text
}

const formatDate = (dateStr: string) => {
  return new Date(dateStr).toLocaleString('zh-CN')
}


// 生命周期
onMounted(() => {
  loadStats()
  loadPostsList()
})
</script>

<style scoped>
.exposure-audit {
  padding: 20px;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 500;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.stats-cards {
  margin-bottom: 24px;
}

.stats-card {
  position: relative;
  overflow: hidden;
}

.stats-content {
  position: relative;
  z-index: 2;
}

.stats-number {
  font-size: 32px;
  font-weight: bold;
  line-height: 1;
  margin-bottom: 8px;
}

.stats-label {
  font-size: 14px;
  color: #909399;
}

.stats-icon {
  position: absolute;
  right: 20px;
  top: 20px;
  font-size: 48px;
  opacity: 0.3;
}

.stats-card.total-posts .stats-number {
  color: #409eff;
}

.stats-card.today-posts .stats-number {
  color: #67c23a;
}

.stats-card.total-comments .stats-number {
  color: #e6a23c;
}

.stats-card.total-likes .stats-number {
  color: #f56c6c;
}

.filter-card {
  margin-bottom: 24px;
}

.table-card {
  margin-bottom: 24px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.post-content {
  max-width: 300px;
}

.content-text {
  margin: 0 0 8px 0;
  line-height: 1.5;
  color: #303133;
}

.content-meta {
  margin-top: 8px;
}

.interaction-stats {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.interaction-stats > div {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #909399;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.post-detail {
  max-height: 70vh;
  overflow-y: auto;
}

.detail-section {
  margin-bottom: 24px;
}

.detail-section h3 {
  margin: 0 0 12px 0;
  color: #303133;
  font-size: 16px;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 8px;
}

.user-detail {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-meta p {
  margin: 4px 0;
  color: #606266;
}

.post-text {
  margin: 0;
  line-height: 1.6;
  color: #303133;
  white-space: pre-wrap;
}

.post-images {
  margin-top: 12px;
}

.stats-detail {
  display: flex;
  gap: 8px;
}

.comments-list {
  max-height: 200px;
  overflow-y: auto;
}

.comment-item {
  padding: 12px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  margin-bottom: 8px;
}

.comment-user {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.comment-time {
  color: #909399;
  font-size: 12px;
}

.comment-content {
  margin: 0 0 8px 0;
  line-height: 1.5;
  color: #606266;
}

.no-comments {
  color: #909399;
  text-align: center;
  margin: 20px 0;
}

.image-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.image-item {
  position: relative;
}

.remove-image {
  position: absolute;
  top: -6px;
  right: -6px;
}

.action-buttons {
  display: flex;
  gap: 8px;
  align-items: center;
}

.action-buttons .el-button {
  margin: 0;
}
</style>